﻿using Autofac;
using MgSoft.Import.Exchange.ExWebApi.Db.Daos;
using MgSoft.Import.Exchange.ExWebApi.Db.Dtos;
using System;
using System.Collections.Generic;
using System.Text;

namespace MgSoft.Import.Exchange.ExWebApi.Db
{
    public abstract class TargetExWebApiTaskManager<TDto, TTask> : ExWebApiTaskManager<TDto, TTask, ISyncDataDao>/*重载Dao，从中间库取数*/
        where TDto : class, IDbExchangeDto
        where TTask : IExchangeTask
    {
        ISyncDataDao syncDataDao;

        /// <summary>
        /// 业务类型，默认Title，注：Source与Target的业务类型必须一致
        /// </summary>
        protected virtual string BillType => Title;

        /// <summary>
        /// 业务类型名称，默认Title
        /// </summary>
        protected virtual string BillTypeName => Title;

        public TargetExWebApiTaskManager(ILifetimeScope lifetimeScope) : base(lifetimeScope)
        {
            syncDataDao = lifetimeScope.Resolve<ISyncDataDao>();
        }

        protected override List<TDto> GetSyncDatas()
        {
            return syncDataDao.GetSyncDatas<TDto>(this.BillType);
        }

        protected override void DoAction(object obj)
        {
            SyncDataDto syncDataDto = null;
            TDto dto = null;
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            try
            {
                dto = obj as TDto;
                syncDataDto = syncDataDao.Get(dto.GetDto_KeyFieldValue(), dto.GetDto_OrgNumberValue(), BillType);
                if (dto == null)
                {
                    return;
                }

                stopwatch.Start();

                //调用Task逻辑
                exchangeTask.Do(dto);

                stopwatch.Stop();

                //执行成功更新字段
                syncDataDto.ErrorMessage = "";
                syncDataDto.IsSyncError = false;
                syncDataDto.State = StateEnum.Complete;
                syncDataDto.LastSyncSucceTime = DateTime.Now;
                syncDataDto.CostTime = stopwatch.ElapsedMilliseconds;

                if (!syncDataDto.FirstSyncSucceTime.HasValue)
                {
                    syncDataDto.FirstSyncSucceTime = DateTime.Now;
                }
            }
            catch (Exception exception)
            {
                if (syncDataDto is null)
                {
                    throw new MgException("TargetExWebApiTaskManager基类错误 ：syncDataDto is null");
                    log.Error("TargetExWebApiTaskManager基类错误 ：syncDataDto is null");
                }
                //写入错误日志
                syncDataDto.ErrorMessage = exception.Message;
                syncDataDto.ErrorStackTrace = exception.StackTrace;
                syncDataDto.IsSyncError = true;
                log.Error("TargetExWebApiTaskManager捕获错误\r\n" + exception.Message + "/r/n" + exception.StackTrace);
                log.Error($"TargetManager Error: Dto:【{dto?.GetDto_KeyFieldValue() ?? "无法获取主键"}】        syncDataDto:【{syncDataDto.Biz_KeyField}】");
            }
            finally
            {
                stopwatch.Stop();

                try
                {
                    syncDataDto.SyncCount++;
                    syncDataDto.SyncTime = DateTime.Now;
                    //更新同步信息
                    syncDataDao.Update(syncDataDto);
                }
                catch (Exception exception)
                {
                    log.Error("TargetExWebApiTaskManager更新数据库错误信息失败\r\n" + exception.Message + "/r/n" + exception.StackTrace);
                }

                if (useThreadPoolFlag)
                {
                    doAction_checkThreadPoolIsEnd();
                }
            }
        }
    }
}
